const Router = require("koa-router");
const { Alioss } = require("@services/alioss");
// const multer = require('@koa/multer');

const router = new Router({
  prefix: "/admin",
});

// // 配置 koa-multer
// const storage = multer.diskStorage({
//   destination:  (req, file, cb) =>{
//     cb(null, "uploads/"); // 保存文件的目录
//   },
//   filename:  (req, file, cb)=> {
//     // 这里可以自定义文件名，但为了简化，我们直接使用原文件名
//     var fileFormat = (file.originalname).split(".");
//         cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
//   },
// });

// const upload = multer({ storage: storage });

// 阿里云图片上传
// router.post("/upload_ali", upload.single("file"), async (ctx, next) => {
//   const file = ctx.request.file;
//   if (!file) {
//     ctx.status = 400;
//     ctx.body = "No file uploaded.";
//     return;
//   }

//   const result = await Alioss.upload(file);

//   // 返回上传结果或文件访问URL
//   ctx.body = {
//     code: 200,
//     msg: "上传成功",
//     data: {
//       url: result.url, // 或者直接返回result对象
//     },
//   };
// });

router.post("/getTag", async (ctx, next) => {
  const { img } = ctx.request.body;
  const res = await Alioss.getTag(img);
  ctx.body = {
    code: 200,
    msg: "获取成功",
    data: {
      tag: res,
    },
  };
});

router.post("/delTag", async (ctx, next) => {
  const { img } = ctx.request.body;
  const res = await Alioss.delTag(img);
  ctx.body = res;
});

// 获取stsToken
router.post("/stsToken", async (ctx, next) => {
  const result = await Alioss.stsToken();

  const now = new Date();
  const year = now.getFullYear(); // 获取年份
  const month = String(now.getMonth() + 1).padStart(2, "0"); // 获取月份，月份从0开始计数，所以要+1，并使用padStart确保是两位数
  const day = String(now.getDate()).padStart(2, "0");
  const ossFileName = `images/${year}-${month}-${day}/`;

  const sts = result.body.credentials;
  ctx.body = {
    code: 200,
    msg: "获取成功",
    filename: ossFileName,
    stsToken: {
      accessKeyId: sts.accessKeyId,
      accessKeySecret: sts.accessKeySecret,
      stsToken: sts.securityToken,
      region: "oss-cn-guangzhou",
      bucket: "cells-plus",
      cname: true,
      endpoint: "https://cdn.cellsplus.top",
    },
  };
});

module.exports = router;
